const express = require('express');
const router = express.Router();
const Activities = require('../../models/activities/activities');
const { Op } = require('sequelize');

// 获取指定社团的所有活动
router.get('/activity/:clubId', async (req, res) => {
  try {
    const { clubId } = req.params;
    const { status } = req.query; // 可选参数：upcoming, ongoing, past, all

    const now = new Date();
    let whereClause = { club_id: clubId };

    // 根据状态筛选活动
    if (status) {
      switch (status) {
        case 'upcoming':
          whereClause.start_time = { [Op.gt]: now };
          break;
        case 'ongoing':
          whereClause = {
            ...whereClause,
            start_time: { [Op.lte]: now },
            end_time: { [Op.gt]: now }
          };
          break;
        case 'past':
          whereClause.end_time = { [Op.lt]: now };
          break;
        case 'all':
          // 不添加时间条件，获取所有活动
          break;
        default:
          return res.status(400).json({
            success: false,
            message: '无效的状态参数'
          });
      }
    }

    const activities = await Activities.findAll({
      where: whereClause,
      order: [['start_time', 'ASC']]
    });

    res.json({
      success: true,
      message: '获取社团活动成功',
      data: activities
    });

  } catch (error) {
    console.error('获取社团活动失败:', error);
    res.status(500).json({
      success: false,
      message: '获取社团活动失败',
      error: error.message
    });
  }
});

// 获取指定活动信息
router.get('/activityDetail/:activityId', async (req, res) => {
  try {
    const { activityId } = req.params;

    const activity = await Activities.findByPk(activityId);

    if (!activity) {
      return res.status(404).json({
        success: false,
        message: '活动未找到'
      });
    }

    res.json({
      success: true,
      message: '获取活动信息成功',
      data: activity
    });

  } catch (error) {
    console.error('获取活动信息失败:', error);
    res.status(500).json({
      success: false,
      message: '获取活动信息失败',
      error: error.message
    });
  }
});

// 获取所有活动信息
router.get('/allActivity', async (req, res) => {
  try {
    const {
      status,
      type,
      page = 1,
      pageSize = 10,
      search
    } = req.query;

    const now = new Date();
    let whereClause = {};

    // 根据状态筛选
    if (status) {
      switch (status) {
        case 'upcoming':
          whereClause.start_time = { [Op.gt]: now };
          break;
        case 'ongoing':
          whereClause = {
            start_time: { [Op.lte]: now },
            end_time: { [Op.gt]: now }
          };
          break;
        case 'past':
          whereClause.end_time = { [Op.lt]: now };
          break;
        case 'all':
          // 不添加时间条件
          break;
        default:
          return res.status(400).json({
            success: false,
            message: '无效的状态参数'
          });
      }
    }

    // 根据类型筛选
    if (type) {
      whereClause.type = type;
    }

    // 搜索功能
    if (search) {
      whereClause = {
        ...whereClause,
        [Op.or]: [
          { title: { [Op.like]: `%${search}%` } },
          { description: { [Op.like]: `%${search}%` } },
          { location: { [Op.like]: `%${search}%` } }
        ]
      };
    }

    // 计算分页
    const offset = (page - 1) * pageSize;
    const limit = parseInt(pageSize);

    // 获取总数
    const total = await Activities.count({ where: whereClause });

    // 获取分页数据
    const activities = await Activities.findAll({
      where: whereClause,
      order: [['start_time', 'ASC']],
      offset,
      limit
    });

    res.json({
      success: true,
      message: '获取活动列表成功',
      data: {
        activities,
        pagination: {
          current: parseInt(page),
          pageSize: limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      }
    });

  } catch (error) {
    console.error('获取活动列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取活动列表失败',
      error: error.message
    });
  }
});

module.exports = router;
